package myky.com.doctorapp.wight;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import myky.com.doctorapp.R;
import myky.com.doctorapp.event.MessageEvent;
import myky.com.doctorapp.utils.RecyclerUtils;

import static myky.com.doctorapp.R.id.my_dialog_box_tv;
import static myky.com.doctorapp.R.style.MyDialog;

/**
 * Created by 61904 on 2016/12/26.
 */


/**
 * 创建自定义的dialog，主要学习其实现原理
 * Created by chengguo on 2016/3/22.
 */
public class SelfDialog extends Dialog {

    private String dialogType;
    private boolean isMyDialog;
    private Button yes;//确定按钮
    private Button no;//取消按钮
    private View line;
    private TextView titleTv;//消息标题文本
    private TextView messageTv;//消息提示文本
    private String titleStr = "";//从外界设置的title文本
    private String messageStr;//从外界设置的消息文本
    private String editMessage;//从外界设置的EditText消息文本
    private String editHintMessage;//从外界设置的EditTextHint消息文本
    //确定文本和取消文本的显示内容
    private String yesStr, noStr;
    private static ProgressDialog mydialog;
    private RecyclerView recyclerView; //单选多选列表
    private EditText editText;  //输入框

    private List<String> stringList;//选项文本集合
    private List<String> backList;//点击确定返回的选项文本集合
    private List<String> sList;////选项用户以选择文本集合

    private int index = -1; //单选下标记录

    public static boolean isShow = false;
    private onNoOnclickListener noOnclickListener;//取消按钮被点击了的监听器
    private onYesOnclickListener yesOnclickListener;//确定按钮被点击了的监听器
    private onYesBackOnclickListener yesOnbackclickListener;//确定按钮被点击了选择的内容回调的监听器
    private CommonAdapter<String> adapter;
    private HeaderAndFooterWrapper mHeaderAndFooterWrapper;
    private boolean hasOthers;
    private EditText editText2;
    private View view;
    private String fragmentType;
    private String editMessage2;
    private List<String> boxList;
    private String otherText;
    private static Context context;
    private Integer btnType = 0;

    //进度条显示框
    public static void progressdialog(Context contexts, String message) {
        context = contexts;
        mydialog = new ProgressDialog(context);
        mydialog.setMessage(message);
        mydialog.setCanceledOnTouchOutside(false);
        mydialog.setCancelable(true);
        mydialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mydialog != null && mydialog.isShowing()) {
                        //此句加上之后先关闭对话框，然后跳转，不加则直接跳转
                        mydialog.dismiss();
                        isShow = false;
                    }
                }
                return true;
            }
        });
        mydialog.show();
        isShow = true;
    }




    //进度条显示框
    public  void creatProgressDialog(Context contexts, String message) {
        context = contexts;
        mydialog = new ProgressDialog(context);
        mydialog.setMessage(message);
        mydialog.setCanceledOnTouchOutside(false);
        mydialog.setCancelable(true);
        mydialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mydialog != null && mydialog.isShowing()) {
                        //此句加上之后先关闭对话框，然后跳转，不加则直接跳转
                        mydialog.dismiss();
                        isShow = false;
                    }
                }
                return true;
            }
        });
        mydialog.show();
        isShow = true;

    }


    //关闭进度条
    public static void dismissdialog() {
        if (mydialog != null && context != null && !((Activity) context).isFinishing()) {
            mydialog.dismiss();
            isShow = false;
        }
    }

    /**
     * 设置取消按钮的显示内容和监听
     *
     * @param str
     * @param onNoOnclickListener
     */
    public void setNoOnclickListener(String str, onNoOnclickListener onNoOnclickListener) {
        if (str != null) {
            noStr = str;
        }
        this.noOnclickListener = onNoOnclickListener;
    }


    /**
     * 设置确定按钮的显示内容和监听
     *
     * @param str
     * @param onYesOnclickListener
     */
    public void setYesOnclickListener(String str, onYesOnclickListener onYesOnclickListener) {
        if (str != null) {
            yesStr = str;
        }
        this.yesOnclickListener = onYesOnclickListener;
    }

    /**
     * 设置确定按钮的显示内容和监听
     *
     * @param str
     */
    public void setYesOnclickListener(String str, onYesBackOnclickListener yesOnbackclickListener) {
        if (str != null) {
            yesStr = str;
        }
        this.yesOnbackclickListener = yesOnbackclickListener;
    }

    public SelfDialog(Context context) {
        super(context, R.style.MyDialog);
        isMyDialog = false;

    }

    //自定义style
    public SelfDialog(Context context, String fragmentTypes, boolean isMyDialog, String dialogTypes, boolean hasOthers) {
        super(context, MyDialog);
        this.isMyDialog = isMyDialog;
        this.dialogType = dialogTypes;
        this.hasOthers = hasOthers;
        this.fragmentType = fragmentTypes;


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (isMyDialog) {
            setContentView(R.layout.myself_dialog_layout);
        } else {
            setContentView(R.layout.free_exercise_sure_dialog_layout);
        }
        //按空白处不能取消动画
        setCanceledOnTouchOutside(false);


        //初始化界面控件
        initView();
        //初始化界面数据
        initData();
        //初始化界面控件的事件
        initEvent();


    }

    /**
     * 初始化界面的确定和取消监听器
     */
    private void initEvent() {
        //设置确定按钮被点击后，向外界提供监听
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (yesOnclickListener != null) {
                    yesOnclickListener.onYesClick();
                }
                if (yesOnbackclickListener != null) {

                    Log.i("out", "backList" + backList);
                    if (dialogType.equals("EditText")) {
                        backList = new ArrayList<String>();
                        String backString = editText.getText().toString().trim();
                        Log.i("out", "backstring" + backString);
                        if (backString != null && !backString.equals("")) {

                            backList.add(backString);
                        }
                        if (titleStr.equals("联系人和电话")) {

                            backList.add(editText2.getText().toString().trim());
                        }
                    }
                    yesOnbackclickListener.onYesClick(backList);
                }
            }
        });
        //设置取消按钮被点击后，向外界提供监听
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (noOnclickListener != null) {
                    noOnclickListener.onNoClick();
                }
            }
        });
    }


    /**
     * 初始化界面控件的显示数据
     */
    private void initData() {
        //如果用户自定了title和message
        if (titleStr != null) {
            titleTv.setText(titleStr);

            if (titleStr.equals("联系人和电话")) {

                editText2.setVisibility(View.VISIBLE);
                editText2.setHint("请填写联系人电话");
                view.setVisibility(View.VISIBLE);
            }
        } else {
//            titleTv.setVisibility(View.GONE);
        }
        if (messageStr != null) {
            messageTv.setText(messageStr);
        } else {
            messageTv.setVisibility(View.GONE);
        }

        //如果设置按钮的文字
        if (yesStr != null) {
            yes.setText(yesStr);
        } else {
            yes.setVisibility(View.GONE);
        }
        if (noStr != null) {
            no.setText(noStr);
        } else {
            no.setVisibility(View.GONE);
        }


        if (isMyDialog) {
            switch (dialogType) {

                case "EditText":
                    //如果用户自定了editMessage和editHintMessage
                    editText.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                    if (editMessage != null) {
                        editText.setText(editMessage);
                    }
                    if (editHintMessage != null) {

                        editText.setHint(editHintMessage);
                    }
                    if (editMessage2 != null) {
                        editText2.setText(editMessage2);
                    }
                    break;

                case "Radio":
                    editText.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    setRecyclerView();//设置单选选项列表
                    break;

                case "Box":
                    editText.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    setRecyclerView();//设置多选选选项列表
                    break;
            }

        }

    }


    /**
     * 初始化界面控件
     */
    private void initView() {
        if (isMyDialog) {
            yes = (Button) findViewById(R.id.my_dialog_yes);
            no = (Button) findViewById(R.id.my_dialog_no);
            line = (View) findViewById(R.id.line);
            titleTv = (TextView) findViewById(R.id.my_dialog_title);
            messageTv = (TextView) findViewById(R.id.my_dialog_message);
            editText = (EditText) findViewById(R.id.my_dialog_et);
            editText2 = (EditText) findViewById(R.id.my_dialog_et2);
            view = findViewById(R.id.my_dialog_v2);
            recyclerView = (RecyclerView) findViewById(R.id.my_dialog_recyclerView);
        } else {
            yes = (Button) findViewById(R.id.yes);
            no = (Button) findViewById(R.id.no);
            line = (View) findViewById(R.id.line);
            titleTv = (TextView) findViewById(R.id.title);
            messageTv = (TextView) findViewById(R.id.message);
        }
        //隐藏掉取消按钮
        if (btnType == 1) {
            line.setVisibility(View.GONE);
        }
    }

    /**
     * 从外界Activity为Dialog设置标题
     */
    public void goneCancelButton() {
        btnType = 1;
    }

    /**
     * 从外界Activity为Dialog设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        titleStr = title;
    }

    /**
     * 从外界Activity为Dialog设置dialog的message
     *
     * @param message
     */
    public void setMessage(String message) {
        messageStr = message;
    }

    /**
     * 从外界Activity为Dialog设置EditText的message
     *
     * @param editText
     */
    public void setEditText(String editText, String editText2, String editHintText) {
        editMessage = editText;
        editMessage2 = editText2;
        editHintMessage = editHintText;
    }

    /**
     * 从外界Activity为Dialog设置单选多选对话框
     */
    public void setSelectionBox(List<String> strings, List<String> sLists, String otherTexts) {
        stringList = strings;
        sList = sLists;
        otherText = otherTexts;

    }

    /**
     * 设置确定按钮和取消被点击的接口
     */
    public interface onYesOnclickListener {
        void onYesClick();
    }


    public interface onYesBackOnclickListener {
        void onYesClick(List<String> strings);
    }

    public interface onNoOnclickListener {

        void onNoClick();
    }


    //设置选项列表
    private void setRecyclerView() {
        //单选和多选列表展示
        if (stringList != null) {
            RecyclerUtils.setRecylerParms(getContext(), recyclerView);
            initAdapter();
            recyclerView.setAdapter(mHeaderAndFooterWrapper);
        }
    }

    public void initAdapter() {
        backList = new ArrayList<>();
        if (sList != null) {
            backList.addAll(sList);
        }
        adapter = new CommonAdapter<String>(getContext(), R.layout.my_dialog_box, stringList) {
            @Override
            protected void convert(final ViewHolder holder, final String s, final int position) {
                final TextView textView = holder.getView(my_dialog_box_tv);
                holder.setText(my_dialog_box_tv, s);
                final ImageView imageView = holder.getView(R.id.my_dialog_box_iv);
                imageView.setImageResource(R.mipmap.css_wxz);
                imageView.setTag(R.mipmap.css_wxz);
                holder.setTextColor(my_dialog_box_tv, Color.parseColor("#d6d6d6"));
                for (int i = 0; i < backList.size(); i++) {
                    if (s.equals(backList.get(i))) {
                        imageView.setImageResource(R.mipmap.yycg_dg);
                        imageView.setTag(R.mipmap.yycg_dg);
                        textView.setTextColor(Color.parseColor("#474747"));
                    }
                }
                switch (dialogType) {
                    case "Radio":

                        holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (position == index) {
                                    imageView.setImageResource(R.mipmap.yycg_dg);
                                    textView.setTextColor(Color.parseColor("#474747"));

                                } else {
                                    imageView.setImageResource(R.mipmap.css_wxz);
                                    textView.setTextColor(Color.parseColor("#d6d6d6"));
                                }

                                index = position;

                                backList.clear();
                                backList.add(s);

                                mHeaderAndFooterWrapper.notifyDataSetChanged();

                            }
                        });

                        break;

                    case "Box":


                        holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {


                                assert (R.id.my_dialog_box_iv == imageView.getId());
                                Integer integer = (Integer) imageView.getTag();
                                integer = integer == null ? 0 : integer;
                                switch (integer) {
                                    case R.mipmap.yycg_dg:
                                        Log.i("out", "imageView_有");
                                        imageView.setImageResource(R.mipmap.css_wxz);
                                        imageView.setTag(R.mipmap.css_wxz);
                                        textView.setTextColor(Color.parseColor("#d6d6d6"));

                                        for (int i = 0; i < backList.size(); i++) {
                                            if (s.equals(backList.get(i))) {
                                                backList.remove(i);
                                                return;
                                            }
                                        }
                                        break;
                                    case R.mipmap.css_wxz:

                                        if (s.equals("无")) {
                                            backList.clear();
                                        } else {
                                            if (backList.contains("无")) {
                                                for (int i = 0; i < backList.size(); i++) {
                                                    if (backList.get(i).equals("无")) {
                                                        backList.remove(i);
                                                        continue;
                                                    }
                                                }
                                            }
                                        }
                                        Log.i("out", "imageView_无");
                                        textView.setTextColor(Color.parseColor("#474747"));
                                        imageView.setImageResource(R.mipmap.yycg_dg);
                                        imageView.setTag(R.mipmap.yycg_dg);
                                        backList.add(s);
                                        mHeaderAndFooterWrapper.notifyDataSetChanged();
                                        break;
                                }

                            }
                        });
                        break;

                }


            }
        };


        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(adapter);

        if (hasOthers) {
            View view = getLayoutInflater().inflate(R.layout.my_dialog_box, null);
            TextView textView = (TextView) view.findViewById(R.id.my_dialog_box_tv);
            if (titleStr.equals("疾病名称")) {
                textView.setText("添加疾病");
            }
            ImageView imageView1 = (ImageView) view.findViewById(R.id.my_dialog_box_iv);
            ImageView imageView2 = (ImageView) view.findViewById(R.id.my_dialog_box_iv2);
            imageView1.setVisibility(View.GONE);
            imageView2.setVisibility(View.VISIBLE);


            mHeaderAndFooterWrapper.addFootView(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    boxList = new ArrayList();
                    if (dialogType.equals("Box")) {

                        if (backList.contains("无")) {
                            for (int i = 0; i < backList.size(); i++) {
                                if (backList.get(i).equals("无")) {
                                    backList.remove(i);
                                    continue;
                                }
                            }
                        }
                        boxList.addAll(backList);
                    }
                    Log.i("out", "boxlist..." + boxList);

                    final SelfDialog selfDialog = new SelfDialog(getContext(), fragmentType, true, "EditText", false);
                    selfDialog.setTitle(titleStr);
                    selfDialog.setEditText(otherText, null, "输入其他" + titleStr);

                    selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesBackOnclickListener() {


                        @Override
                        public void onYesClick(List<String> strings) {

                            String str = null;


                            if (strings.size() == 0) {
                                str = "";
                            } else {
                                str = strings.get(0);
                            }

                            if (titleStr.equals("疾病名称")) {

                                backList.add(str);
                                stringList.clear();
                                stringList.addAll(backList);
                                mHeaderAndFooterWrapper.notifyDataSetChanged();
                            } else {
                                EventBus.getDefault().post(new MessageEvent.MessageHealthOthers(boxList, str, fragmentType));
                            }
                            selfDialog.dismiss();
                        }
                    });

                    selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            selfDialog.dismiss();
                        }
                    });

                    selfDialog.show();
                }
            });

        }


    }


}





